<?php

namespace app\models\user;

use app\components\Fun;
use app\components\Lcms;
use app\models\User;
use Yii;

/**
 * This is the model class for table "{{%avatar}}".
 *
 * @property int $id
 * @property int|null $uid 用户的id
 * @property string|null $jiguang_id 极光id
 * @property string|null $file 服务器文件地址
 * @property string|null $url 对外公开地址
 * @property int|null $time 更新头像地址时间
 */
class AvatarModel extends \app\models\BaseUserModel
{
    /**
     * {@inheritdoc}
     */
    public static function tableName()
    {
        return '{{%avatar}}';
    }

    /**
     * {@inheritdoc}
     */
    public function rules()
    {
        return [
            [['uid', 'time'], 'integer'],
            [['jiguang_id'], 'string', 'max' => 255],
            [['file', 'url'], 'string', 'max' => 255],
            [['uid'], 'unique'],
            [['jiguang_id'], 'unique'],
        ];
    }

    /**
     * {@inheritdoc}
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'uid' => 'Uid',
            'jiguang_id' => 'Jiguang ID',
            'file' => 'File',
            'url' => 'Url',
            'time' => 'Time',
        ];
    }



    /**
     * 修改用户头像
    */
    public static function upUserAvatar($file,$img,$uid){
        $count=self::updateAll([
            'file'=>$file,
            'url'=>$img,
            'time'=>time()
        ],[
            'uid'=>$uid
        ]);
        if($count==1){
            return true;
        }
        $one=new self;
        $usermodel=User::find()->where([
            'id'=>$uid
        ])->one();
        $one->uid=$usermodel->id;
        $one->jiguang_id=$usermodel->jiguang_id;
        $one->file=$file;
        $one->url=$img;
        $one->time=time();
        return $one->save();
    }


    /**
     * 加载图片数据,并读取文件内容返回
    */
    public static function getAvatarData($jid,$uid){
        $file=Yii::getAlias('@webroot') . '/public/defaultavatar.jpg';
        $one=null;
        if($jid!==''){
            $one=self::find()->where([
                'jiguang_id'=>$jid
            ])->select('file')->one();
        }elseif($uid!==''){
            $one=self::find()->where([
                'uid'=>$uid
            ])->select('file')->one();
        }else{
            $one=null;
        }

        if($one&&is_file($one->file)){
            $file=$one->file;
        }
        return file_get_contents($file);
    }


























}
